#include "medialocator.h"
#include <phonon>

MediaLocator::MediaLocator() {
    listenedFolders=new QList<MediaFolder *>();
    files= new QList<MediaFile *>();
    extensions=new QStringList();
    QSqlQueryModel * model= Querier::getModel("SELECT * FROM ListenedFolders");
    for(int i=0; i<model->rowCount(); i++) {
        MediaFolder * folder=new MediaFolder(model->record(i).value("folderID").toLongLong(),model->record(i).value("path").toString());
        //qDebug() <<"folderID: " << folder->folderID;
        QDir directory=QDir(folder->path);
        if(folder->path.startsWith(".")) {
            directory=QDir(qApp->applicationDirPath());
            #if defined(Q_OS_WIN)
                if (directory.dirName().toLower() == "debug" || directory.dirName().toLower() == "release")
                    directory.cdUp();
            #elif defined(Q_OS_MAC)
                    directory.cdUp();
                    directory.cdUp();
                    directory.cdUp();
            #endif
            //qDebug()<<directory.absolutePath();
            QString path=folder->path;
            int start=path.indexOf("/");
            path=path.mid(start+1);

            directory.cd(path);
            folder->path=directory.absolutePath();
            //qDebug()<<"adjusted path is "<<folder->path;
        }
        listenedFolders->append(folder);
    }

    model= Querier::getModel("SELECT * FROM Extensions");
    for(int i=0; i<model->rowCount(); i++) {
        extensions->append("*"+model->record(i).value("extension").toString());
        //qDebug()<<extensions->at(i);
    }
    //qDebug()<<"extensions in db "<<extensions->size()<<"rows"<<model->rowCount();
    foreach(MediaFolder * folder, *listenedFolders) {
        QString query="SELECT * FROM MediaFiles mf WHERE mf.folderID='"+(folder->folderID);
        query+="'";
        QSqlQueryModel * model= Querier::getModel(query);
        if(model) {
            for(int i=0; i<model->rowCount(); i++) {
                MediaFile * file=new MediaFile();
                file->mediaID=model->record(i).value("mediaID").toInt();
                file->shortName=model->record(i).value("fileName").toString();
                file->coverArt=model->record(i).value("coverArt").toString();
                //qDebug()<<"using "<<folder->path;
                file->fileLocation=folder->path;
                files->append(file);
            }
        }
    }

}

void MediaLocator::rescan() {
    mutex->lock();
        condition.wakeAll();
    mutex->unlock();
}

void MediaLocator::addFolder(long long id,QString folder) {
    mutex->lock();
        MediaFolder * newFolder=new MediaFolder(id,folder);
        listenedFolders->append(newFolder);
    mutex->unlock();
}

void MediaLocator::removeFolder(QString folder) {
    mutex->lock();
        foreach(MediaFolder * lFolder, *listenedFolders) {
            if(lFolder->path==folder) {
                listenedFolders->removeAll(lFolder);
            }
        }
    mutex->unlock();
}



void MediaLocator::run() {
    QList<long long> validIDs;
    valid="";
    mutex=new QMutex();
    //MediaChecker * checker=new MediaChecker();
    forever {
        mutex->lock();

        foreach(MediaFolder * folder, * listenedFolders) {
            scanFolder(folder->folderID,folder->path,"");
            /*qDebug()<<"folder: "<<folder->path;
            QDir directory=QDir(folder->path);
            qDebug()<<directory.exists();
            if(directory.exists()) {
                QStringList files=directory.entryList(QDir::Files, QDir::Unsorted);
                //qDebug() <<files;
                foreach(QString file, files) {
                    //qDebug()<<"folder: "<<directory.path()<<"file: "<<file;
                    MediaFile * mediaFile=new MediaFile();
                    mediaFile->fileLocation=folder->path;
                    mediaFile->shortName=file;
                    mediaFile->folderID=folder->folderID;
                    //qDebug() <<"is valid file "<<checker->checkValid(mediaFile);
                    int number=Querier::addMediaFile(mediaFile);
                    if(number>=0) {
                        if(valid.length()>0) {
                            valid+=", ";
                        }
                        valid+="'";

                        valid+=QString::number(number);
                        valid+="'";
                        this->files->append(mediaFile);
                    }
                }
            }*/
        }
        //qDebug()<<valid;
        Querier::getResult("UPDATE MediaFiles SET accessible='0' WHERE mediaID NOT IN ("+valid+")");
        Querier::getResult("UPDATE MediaFiles SET accessible='1' WHERE mediaID IN ("+valid+")");
        //wait two minutes and scan again
        condition.wait(mutex,2*1000.0*60.0);
        mutex->unlock();
    }
}

void MediaLocator::scanFolder(int id, QString directory, QString subdirectory) {
    qDebug()<<"scanning directory"<<directory<<"in subdirectory:"<<subdirectory;
    QString f=directory;
    if(subdirectory.size()>0) {
        f+=subdirectory;
    }
    QDir folder=QDir(f);
    //scan files in directory
    QStringList files=folder.entryList(QDir::Files, QDir::Unsorted);
    //qDebug() <<files;
    foreach(QString file, files) {
        qDebug()<<"file: "<<file;
        MediaFile * mediaFile=new MediaFile();
        mediaFile->fileLocation=directory+"/"+subdirectory;
        mediaFile->shortName=file;
        mediaFile->folderID=id;
        //qDebug() <<"is valid file "<<checker->checkValid(mediaFile);
        int number=Querier::addMediaFile(mediaFile,subdirectory);
        if(number>=0) {
            if(valid.length()>0) {
                valid+=", ";
            }
            valid+="'";

            valid+=QString::number(number);
            valid+="'";
            this->files->append(mediaFile);
        }
    }
    //scan subdirectories
    files=folder.entryList(QDir::Dirs, QDir::Unsorted);
    //qDebug() <<files;
    foreach(QString file, files) {
        if(!file.startsWith(".")) {
            scanFolder(id, directory,QString(subdirectory+"/"+file));
        }
    }
}


